import 'dart:async';
import 'package:flutter_livepush_plugin/base/live_base.dart';
import 'package:flutter_livepush_plugin/base/live_base_def.dart';
import 'package:flutter_livepush_plugin/pusher/live_push_config.dart';
import 'package:flutter_livepush_plugin/pusher/live_push_def.dart';
import 'package:flutter_livepush_plugin/pusher/live_pusher.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/live/live_detail_entity.dart';
import 'package:sports_new/entity/live/expert_room_entity.dart';
import 'package:sports_new/server/api/live_api.dart';
import 'package:sports_new/utils/image_utils.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';

class LivePushLogic extends GetxController{
  AlivcLivePusher livePusher = AlivcLivePusher.init();
  AlivcLivePushConfig config = AlivcLivePushConfig.init();
  ExpertRoomEntity info = Get.arguments;
  LiveDetailEntity? liveDetail;
  Timer? _timer;
  Timer? _countTimer;
  bool _onPush = false;
  bool _mirror = false;
  bool _clickStart = false;
  int _count = 3;

  bool get onPush => _onPush;
  int get count => _count;
  bool get mirror => _mirror;
  bool get clickStart => _clickStart;

  set clickStart(bool value) {
    _clickStart = value;
    update();
  }
  set mirror(bool value) {
    _mirror = value;
    update();
  }
  set count(int value) {
    _count = value;
    update();
  }
  set onPush(bool value) {
    _onPush = value;
    update();
  }

  @override
  void onInit() async{
    await ImageUtils.getLivePermission();
    getData();
    AlivcLiveBase.setListener(AlivcLiveBaseListener(
      onLicenceCheck: (AlivcLiveLicenseCheckResultCode result, String reason) {
        if (result == AlivcLiveLicenseCheckResultCode.success) {

        }else{
          ToastUtils.show("初始化失败");
        }
      },
    ));
    AlivcLiveBase.setConsoleEnable(true);
    await AlivcLiveBase.registerSDK();
    livePusher.createConfig();
    config.setPreviewDisplayMode(AlivcPusherPreviewDisplayMode.preview_aspect_fill);
    livePusher.initLivePusher();
    livePusher.setOnConnectFail((errorCode, errorDescription) {

    });
    livePusher.setOnNetworkPoor(() {
      ToastUtils.show("当前网络不稳定");
    });
    livePusher.startPreview();
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) => getData());
    super.onInit();
  }

  Future startPush() async{
    onPush = true;
    await livePusher.startPushWithURL(info.pushUrl??"");
  }

  Future stopPush() async{
    if(!onPush) return;
    await livePusher.stopPush();
  }

  Future getData() async{
    liveDetail = await LiveApi.getLiveDetail(info.id);
    update();
  }

  Future start() async{
    count = 3;
    clickStart = true;
    _countTimer = Timer.periodic(const Duration(seconds: 1),
      (timer) async{
        count--;
        if(count == 0){
          startPush();
          LiveApi.startLive(info.id??0);
          timer.cancel();
        }
      });
  }

  Future exit() async{
    if(onPush){
      var result = await Get.dialog(
        const QkdDialog.alert(
          "确定关闭直播间吗？",
          content: "关闭直播间后，需要重新创建直播间，请谨慎选择",
          confirmText: "确认关播",
          confirmTime: 3
        )
      );
      if(result) {
        stopPush();
        await LiveApi.closeLive(info.id??0);
        Get.offAndToNamed(Routes.liveStatistics, arguments: liveDetail?.liveId);
      }
    }else{
      _countTimer?.cancel();
      Get.back();
    }
  }

  void setCamera(){
    livePusher.switchCamera();
  }

  void setMirror(){
    mirror = !mirror;
    livePusher.setPreviewMirror(mirror);
    livePusher.setPushMirror(mirror);
  }

  @override
  void onClose() {
    stopPush();
    _timer?.cancel();
    livePusher.destroy();
    super.onClose();
  }
}